package com.peanut.controller;

import com.peanut.common.Result;
import com.peanut.em.ResultEnum;
import com.peanut.domain.po.TabUser;
import com.peanut.service.ManagerService;
import io.swagger.annotations.ApiOperation;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Objects;

@Component
@RequestMapping("managerController")
public class ManagerController {
    @Resource
    private RocketMQTemplate rocketMQTemplate;
    @Autowired
    private ManagerService managerService;
    @Autowired
    private RedisTemplate redisTemplate;


    @RequestMapping("checkPhone")
    @ResponseBody
    @ApiOperation("发送验证码")
    public Result checkPhone(String phone) {
        try {
            //发送mq消息
            rocketMQTemplate.convertAndSend("phoneNum_Topic", phone);
            return Result.R(ResultEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.R(ResultEnum.ERROR).setData(e);
        }
    }


    @PostMapping("login")
    @ResponseBody
    @ApiOperation("登录")
    public Result login(String phone, String code) {
        // 判断手机号是否为空
        if (Objects.isNull(phone)) {
            return Result.R(ResultEnum.PHONE_NULL);
        }
        // 判断验证码是否为空
        if (Objects.isNull(code)) {
            return Result.R(ResultEnum.CODE_NULL);
        }
        Result result = managerService.login(phone, code);
        return Result.R(ResultEnum.ERROR).setData(result);
    }


    @RequestMapping("register")
    @ResponseBody
    @ApiOperation("注册")
    public Result register(TabUser user, String code) {
        //从redis中取出存入的验证码
        String getCode = redisTemplate.opsForValue().get(user.getPhone(), 0, -1);
        // 校验验证码是否正确
        if (!code.equals(getCode)) {
            return Result.R(ResultEnum.CODE_FAULT);
        }
        return managerService.addUser(user);
    }
}